﻿
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Management;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Pitaya_IDE
{
    public class Search_Device:Panel
    {
        List<Pitaya_Device> Device_list = new List<Pitaya_Device>();
        Form1 form1;

        public Search_Device(Form1 _form1)
        {
            form1 = _form1;
        }

        List<string> SearchIP_list = new List<string>();  //ip列表
        private int SearchTimeout = 50;  //搜索单个设备超时时间
        public void SearchStart()
        {
            Thread tmp = new Thread(do_Search);
            tmp.Start();
        }

        private bool Search_status = false;  //搜索状态

        private void do_Search(object obj)
        {
            if (Search_status) return;

            Search_status = true;

            Device_list.Clear();
            Controls.Clear();

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection nics = mc.GetInstances();

            foreach (ManagementObject nic in nics)
            {
                if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                {
                    string _myHostIP = (nic["IPAddress"] as String[])[0];
                    string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.'));
                    for (int i = 0; i < 255; i++)
                    {
                        SearchIP_list.Add(ipDuan + "." + i);
                    }
                }
            }

            Thread[] tmp = new Thread[16];
            for (int i = 0; i < 16; i++)
            {
                tmp[i] = new Thread(_do_Search);
                tmp[i].Start(i);
            }

            while (true)
            {
                bool status = true;

                for (int i = 0; i < 16; i++)
                {
                    if (tmp[i].IsAlive)
                    {
                        status = false;
                    }
                }

                if (status)
                {
                    Search_status = false;
                    break;
                }

                Thread.Sleep(100);
            }

            /* 清空搜索ip列表 */

            SearchIP_list.Clear();
        }


        private void _do_Search(object obj)
        {
            int start = (int)obj;


            byte[] tmp_data = new byte[1024];
            int Length;

            Socket clientSocket ;
            Pitaya_Device pitaya_out = null;

            for (int i = start; i < SearchIP_list.Count; i+=16)
            {
                string ip_str = SearchIP_list[i];

                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult connResult = clientSocket.BeginConnect(ip_str, 46897, null, null);
                connResult.AsyncWaitHandle.WaitOne(SearchTimeout, true);

                if (!connResult.IsCompleted)
                {
                    clientSocket.Close();
                    clientSocket.Dispose();
                    continue;
                }
                try
                {
                    clientSocket.Send(Encoding.UTF8.GetBytes("网络上位机"));
                    Length = clientSocket.Receive(tmp_data);
                }
                catch (SocketException){
                    clientSocket.Close();
                    clientSocket.Dispose();
                    continue;
                }
                catch (ObjectDisposedException)
                {
                    clientSocket.Close();
                    clientSocket.Dispose();
                    continue;
                }

                clientSocket.Close();
                clientSocket.Dispose();

                string str = Encoding.UTF8.GetString(tmp_data);
                string[] sArray = str.Split(new char[1] { ':' });
                
                if (sArray.GetUpperBound(0) == 3)
                {
                    Pitaya_Device tmp_Device = form1.target_device;

                    if (tmp_Device != null && tmp_Device.Pitaya_ID != null && tmp_Device.Pitaya_ID.Equals(sArray[3]))
                    {
                        pitaya_out = form1.target_device;
                    }
                    else
                    {
                        pitaya_out = new Pitaya_Device(form1)
                        {
                            Device_type = sArray[0],
                            Device_name = sArray[1],
                            sig_intensity = sArray[2],
                            Pitaya_ID = sArray[3],

                            Conn_par = new _conn_par()
                            {
                                ip = ip_str,
                                Search_port = 46897,
                                Control_port = 46898,
                                Image_port = 46899,
                            },
                        };
                    }
                }
                else  continue;

                Device_list.Add(pitaya_out);
                pitaya_out.Set_update_callback(form1.Update_device_display);
                form1.Update_device_display();
            }
        }

        /**
         * 绘制搜索结果面板
         */

        public void Do_Update_device_display()
        {

            Controls.Clear();

            if (form1.panel5_vis && form1.panel24.Visible )
            {

                if (Device_list.Count == 0) return;

                this.Width = this.Parent.Width;
                
                foreach (Pitaya_Device tmp in Device_list)
                {
                    Color backcolor;
                    Point point;

                    if (tmp.choose_sta == 1 && tmp.conn_sta == 1)  //根据连接状态上色
                    {
                        backcolor = Color.FromArgb(0, 144, 241);
                    }
                    else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 1)  ///选中正在连接
                    {
                        backcolor = Color.FromArgb(255, 166, 87);
                    }
                    else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 0)  ///断开连接
                    {
                        backcolor = Color.FromArgb(255, 80, 60);
                    }
                    else
                    {
                        backcolor = Color.FromArgb(18, 22, 25);
                    }

                    if (this.Controls.Count == 0)
                    {
                        point = new Point(2, 0);
                    }
                    else
                    {
                        var _tmp = Controls[Controls.Count - 1];
                        point = new Point(2, _tmp.Top + _tmp.Height + 2);
                    }

                    Panel panel_tmp = new Panel
                    {
                        Name = "panel_" + tmp.Device_name,
                        Size = new Size(this.Parent.Width, 100),
                        Location = point,
                        BackColor = backcolor,
                        Cursor = Cursors.Hand
                    };
                    panel_tmp.MouseDown += new MouseEventHandler(Search_MouseDown);
                    panel_tmp.MouseUp += new MouseEventHandler(Search_MouseUp);
                    panel_tmp.MouseEnter += new EventHandler(Search_MouseEnter);
                    panel_tmp.MouseLeave += new EventHandler(Search_MouseLeave);

                    Controls.Add(panel_tmp);

                    Label label = new Label
                    {
                        Name = "label_" + tmp.Device_name,
                        Size = new Size(this.Parent.Width, 100),
                        Location = new Point(32, 0),
                        BackColor = backcolor,
                        ForeColor = Color.FromArgb(210, 210, 210),
                        Text = tmp.Device_type + ":" + tmp.Device_name,
                        Font = new Font("等线", 13),
                        TextAlign = ContentAlignment.MiddleLeft,
                        Cursor = Cursors.Hand
                    };

                    label.MouseDown += new MouseEventHandler(Search_MouseDown);
                    label.MouseUp += new MouseEventHandler(Search_MouseUp);
                    label.MouseEnter += new EventHandler(Search_MouseEnter);
                    label.MouseLeave += new EventHandler(Search_MouseLeave);

                    panel_tmp.Controls.Add(label);
                }
            }
        }



        string mousedown = null;

        private void Search_MouseUp(object sender, EventArgs e)
        {
            int num;
            string device_name;
            Pitaya_Device tmp = null;

            try
            {
                Panel panel = (Panel)sender;
                num = panel.Name.Length;
                device_name = panel.Name.Substring(6, num - 6);
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                num = label.Name.Length;
                device_name = label.Name.Substring(6, num - 6);
            }

            if (!device_name.Equals(mousedown)) return;

            /*通过一次遍历找到对应的设备*/
            foreach (Pitaya_Device _tmp in Device_list)
            {
                if (_tmp.Device_name.Equals(device_name))
                {
                    tmp = _tmp;
                    break;
                }
            }

            if (tmp == null)
            {
                return;
            }

            Thread _conn_Pitaya = new Thread(Do_conn_Pitaya);
            _conn_Pitaya.Start(tmp);
        }
        private void Search_MouseDown(object sender, EventArgs e)
        {
            int num;

            try
            {
                Panel panel = (Panel)sender;
                num = panel.Name.Length;
                mousedown = panel.Name.Substring(6, num - 6);
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                num = label.Name.Length;
                mousedown = label.Name.Substring(6, num - 6);
            }
        }
        private void Search_MouseEnter(object sender, EventArgs e)
        {
            int num;
            string device_name;
            Pitaya_Device tmp = null;
            Color backcolor;

            try
            {
                Panel panel = (Panel)sender;
                num = panel.Name.Length;
                device_name = panel.Name.Substring(6, num - 6);
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                num = label.Name.Length;
                device_name = label.Name.Substring(6, num - 6);
            }

            /*通过一次遍历找到对应的设备*/
            foreach (Pitaya_Device _tmp in Device_list)
            {
                if (_tmp.Device_name.Equals(device_name))
                {
                    tmp = _tmp;
                    break;
                }
            }

            if (tmp == null)
            {
                return;
            }

            if (tmp.choose_sta == 1 && tmp.conn_sta == 1)  //根据连接状态上色
            {
                backcolor = Color.FromArgb(0, 144, 241);
            }
            else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 1)  ///选中正在连接
            {
                backcolor = Color.FromArgb(255, 190, 110);
            }
            else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 0)  ///断开连接
            {
                backcolor = Color.FromArgb(255, 100, 70);
            }
            else
            {
                backcolor = Color.FromArgb(38, 42, 45);
            }

            try
            {
                Panel panel = (Panel)sender;
                panel.BackColor = backcolor;
                foreach (Control tmp_ in panel.Controls)
                {
                    tmp_.BackColor = backcolor;
                }
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                label.BackColor = backcolor;
                if (label.Parent != null) label.Parent.BackColor = backcolor;
            }
        }
        private void Search_MouseLeave(object sender, EventArgs e)
        {
            int num;
            string device_name;
            Pitaya_Device tmp = null;
            Color backcolor;

            try
            {
                Panel panel = (Panel)sender;
                num = panel.Name.Length;
                device_name = panel.Name.Substring(6, num - 6);
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                num = label.Name.Length;
                device_name = label.Name.Substring(6, num - 6);
            }

            /*通过一次遍历找到对应的设备*/
            foreach (Pitaya_Device _tmp in Device_list)
            {
                if (_tmp.Device_name.Equals(device_name))
                {
                    tmp = _tmp;
                    break;
                }
            }

            if (tmp == null)
            {
                return;
            }

            if (tmp.choose_sta == 1 && tmp.conn_sta == 1)  //根据连接状态上色
            {
                backcolor = Color.FromArgb(31, 111, 235);
            }
            else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 1)  ///选中正在连接
            {
                backcolor = Color.FromArgb(255, 166, 87);
            }
            else if (tmp.choose_sta == 1 && tmp.conn_sta == 0 && tmp.connecting == 0)  ///断开连接
            {
                backcolor = Color.FromArgb(255, 80, 60);
            }
            else
            {
                backcolor = Color.FromArgb(18, 22, 25);
            }

            try
            {
                Panel panel = (Panel)sender;
                panel.BackColor = backcolor;
                foreach (Control tmp_ in panel.Controls)
                {
                    tmp_.BackColor = backcolor;
                }
            }
            catch (InvalidCastException)
            {
                Label label = (Label)sender;
                label.BackColor = backcolor;
                if (label.Parent != null) label.Parent.BackColor = backcolor;

            }

        }


        void Do_conn_Pitaya(object obj)
        {
            Pitaya_Device tmp = (Pitaya_Device)obj;

            if (tmp.conn_sta == 0)
            {
                foreach (Pitaya_Device s_tmp in Device_list)
                {
                    if (s_tmp.choose_sta == 1)
                    {
                        s_tmp.Disconnect();
                        s_tmp.choose_sta = 0;
                    }
                }
                tmp.choose_sta = 1;
                tmp.Pitaya_conn();
                form1.target_device = tmp;
            }
            else
            {
                tmp.Disconnect();
                tmp.choose_sta = 0;
                form1.target_device = null;
            }
        }
    }
}